# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.

import tkinter as tk
from tkinter import ttk
import datetime
import history_db

from serial_comm import SerialComm
from ui.history_detail import HistoryDetailFrame
from ui.history_list import HistoryListFrame
from ui.param_preset import ParamPresetFrame
from ui.serial_settings import SerialSettingsFrame
from ui.test_result import TestResultFrame


class MainApp(tk.Tk):
    def __init__(self):
        history_db.init_db()
        super().__init__()
        self.title("TFT串口助手")
        #self.state('zoomed')  # 启动时全屏
        self.geometry("1500x950")  # 可选：如需保留窗口大小可注释掉
        self.serial_comm = SerialComm()
        self._build_ui()

    def _build_ui(self):
        # 主窗口
        self.left_container = tk.Frame(self)
        self.left_container.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

        self.serial_frame = SerialSettingsFrame(self.left_container, self.serial_comm)
        self.serial_frame.pack(fill=tk.X, padx=10, pady=5)
        # 横向排列参数预设和历史记录
        self.param_frame_container = tk.Frame(self.left_container)
        self.param_frame_container.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
        self.param_frame_vg = ParamPresetFrame(self.param_frame_container, self.serial_comm, "Vg", 0x01)
        self.param_frame_vg.pack(side=tk.LEFT, anchor='n', padx=5, pady=5)  # 顶部对齐，不拉伸
        self.param_frame_vd = ParamPresetFrame(self.param_frame_container, self.serial_comm, "Vd", 0x02)
        self.param_frame_vd.pack(side=tk.LEFT, anchor='n', padx=5, pady=5)  # 顶部对齐，不拉伸
        # 测试结果模块保持原位
        self.test_frame = TestResultFrame(self.left_container, self.serial_comm, main_app=self)
        self.test_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
        
        # 通信日志区域放在test_result下方
        self.log_frame = ttk.LabelFrame(self.left_container, text="通信日志")
        self.log_frame.pack(side=tk.BOTTOM, fill=tk.X, padx=10, pady=5)
        
        # 日志文本框和滚动条
        log_text_frame = ttk.Frame(self.log_frame)
        log_text_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
        
        self.log_text = tk.Text(log_text_frame, height=8, wrap=tk.WORD, state=tk.DISABLED)
        log_scrollbar = ttk.Scrollbar(log_text_frame, orient=tk.VERTICAL, command=self.log_text.yview)
        self.log_text.config(yscrollcommand=log_scrollbar.set)
        
        self.log_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        log_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # 日志控制按钮
        log_btn_frame = ttk.Frame(self.log_frame)
        log_btn_frame.pack(fill=tk.X, padx=5, pady=5)
        
        clear_log_btn = ttk.Button(log_btn_frame, text="清除日志", command=self.clear_log)
        clear_log_btn.pack(side=tk.LEFT, padx=5)

        # 初始状态：vg扫描，vd定值
        self.param_frame_vg.set_mode("扫描")
        self.param_frame_vd.set_mode("定值")

        # 互斥切换逻辑
        self.param_frame_vg.mode_var.trace_add('write', self._on_vg_mode_change)
        self.param_frame_vd.mode_var.trace_add('write', self._on_vd_mode_change)



        # 右区块
        self.right_container = tk.Frame(self)
        self.right_container.pack(side=tk.LEFT, fill=tk.BOTH, expand=False)

        self.history_list_frame = HistoryListFrame(self.right_container, self.on_select_history)
        self.history_list_frame.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
        self.history_detail_frame = HistoryDetailFrame(self.right_container)
        self.history_detail_frame.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
        # 所有控件创建完后再刷新历史记录
        self.history_list_frame.refresh()
        
        # 设置各模块的日志回调
        self.test_frame.set_log_callback(self.add_log)
        self.param_frame_vg.set_log_callback(self.add_log)
        self.param_frame_vd.set_log_callback(self.add_log)


    def _on_vg_mode_change(self, *args):
        vg_mode = self.param_frame_vg.mode_var.get()
        vd_mode = self.param_frame_vd.mode_var.get()
        if vg_mode == "扫描" and vd_mode != "定值":
            self.param_frame_vd.set_mode("定值")
        elif vg_mode == "定值" and vd_mode != "扫描":
            self.param_frame_vd.set_mode("扫描")

    def _on_vd_mode_change(self, *args):
        vd_mode = self.param_frame_vd.mode_var.get()
        vg_mode = self.param_frame_vg.mode_var.get()
        if vd_mode == "扫描" and vg_mode != "定值":
            self.param_frame_vg.set_mode("定值")
        elif vd_mode == "定值" and vg_mode != "扫描":
            self.param_frame_vg.set_mode("扫描")

    def on_select_history(self, record):
        self.history_detail_frame.show_record(record)
    
    def add_log(self, message, log_type="INFO", module=""):
        """添加日志信息到统一日志区域"""
        timestamp = datetime.datetime.now().strftime("%H:%M:%S.%f")[:-3]
        module_prefix = f"[{module}] " if module else ""
        log_entry = f"[{timestamp}] {module_prefix}{log_type}: {message}\n"
        
        self.log_text.config(state=tk.NORMAL)
        self.log_text.insert(tk.END, log_entry)
        self.log_text.see(tk.END)  # 自动滚动到底部
        self.log_text.config(state=tk.DISABLED)
    
    def clear_log(self):
        """清除所有日志"""
        self.log_text.config(state=tk.NORMAL)
        self.log_text.delete(1.0, tk.END)
        self.log_text.config(state=tk.DISABLED)

if __name__ == "__main__":
    app = MainApp()
    app.mainloop()

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
